package com.tmall.tmall.controller.admin;

import com.tmall.tmall.mapper.UserMapper;
import com.tmall.tmall.pojo.PageRt;
import com.tmall.tmall.pojo.Result;
import com.tmall.tmall.pojo.User;
import com.tmall.tmall.pojo.UserLogin;
import com.tmall.tmall.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.security.NoSuchAlgorithmException;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/admin")
public class AdminUserController {
    @Autowired
    private UserService userService;

    /**
     * 分页查询
     * @param pageNum
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public Result Page(@RequestParam(defaultValue = "1") Integer pageNum,
                       @RequestParam(defaultValue = "10") Integer pageSize,
                       String name){
        PageRt list=userService.page(pageNum,pageSize,name);
        return Result.success(list);
    }

    /**
     * 添加用户
     * @param userLogin
     * @return
     * @throws NoSuchAlgorithmException
     */
    @PostMapping("/add")
    public Result add(@RequestBody UserLogin userLogin) throws NoSuchAlgorithmException {
        if(userLogin.getPassword()==null){
            userLogin.setPassword("123456");
        }
        User user = userService.getByName(userLogin);
        if(user!=null){
            return Result.error("用户名重复");
        }
        userService.insert(userLogin);
        return Result.success();
    }
    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id){
        User user = userService.getById(id);
        return Result.success(user);
    }
    /**
     * 更改用户信息
     * @param user
     * @return
     */
    @PutMapping("/update")
    public Result update(@RequestBody User user) throws NoSuchAlgorithmException {
        userService.update(user);
        return Result.success();
    }

    /**
     * 删除用户
     * @param ids
     * @return
     */
    @DeleteMapping("/delBatch")
    public Result deleteByIds(@RequestBody List<Integer> ids){
        userService.deleteByIds(ids);
        return Result.success();
    }

    @PostMapping("/updatePassword")
    public Result updatePassword(@RequestBody UserLogin userLogin) {
        try {
            userService.updatePassword(userLogin.getId(), userLogin.getOldPassword(), userLogin.getPassword());
            return Result.success();
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
}
